package com.example.myproject5

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.gridlayout.widget.GridLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.children
import com.example.cardgame.model.CardMatchingGame
import android.content.Intent
import android.app.Activity

class ThirdActivity : ComponentActivity(),View.OnClickListener  {

    lateinit var game: CardMatchingGame

    val cardButtons = mutableListOf<Button>()
    @SuppressLint("MissingInflatedId")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_third)
        val gridLayout = findViewById<GridLayout>(R.id.gridLayout)
        for (v in gridLayout.children) {
            if (v is Button) {
                v.setOnClickListener(this)
                cardButtons.add(v)
            }
        }
        game = CardMatchingGame(cardButtons.count())
        updateUI()

        val reset = findViewById<Button>(R.id.button_reset)
        reset.setOnClickListener {
            game = CardMatchingGame(cardButtons.count())
            updateUI()
        }

        // 添加返回按钮监听
        val backButton = findViewById<Button>(R.id.button_back)
        backButton.setOnClickListener {
            returnToMainActivity()
        }
    }

    override fun onBackPressed() {
        returnToMainActivity()
    }
    private fun returnToMainActivity() {
        val intent = Intent()
        intent.putExtra(SCORE, game.score)
        setResult(Activity.RESULT_OK, intent)
        finish()
    }
    fun updateUI(){
        for (button in cardButtons){
            val index = cardButtons.indexOf(button)
            val card = game.cardAtIndex(index)
            button.isEnabled = !card.isMatched
            if(card.isChosen) {
                button.text = card.toString()
                button.setBackgroundColor(Color.WHITE)
            }
            else{
                button.text = ""
                button.setBackgroundResource(R.drawable.pig)
            }
        }
        val score = findViewById<TextView>(R.id.textView)
        score.text = String.format("%s%d",getString(R.string.score),game.score)
    }
    override fun onClick(v: View?){
        if (v is Button) {
            val index = cardButtons.indexOf(v)
            game.chooseCardAtIndex(index)
            updateUI()
        }
    }
}